package com.kkd.kkdapp.activity;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;

import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.MyProgressbar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 天天赚详情
 * 
 * @author mty
 * 
 */
public class EveryDayParticularsActivity extends BaseActivity implements
		OnClickListener {

	private final int ACCOUNTINFO_CODE_ELSE = 1; // 余额code=其它

	private RelativeLayout title_img;// 后退
	private TextView mTitle; // 标题
	private TextView mDispark; // 开放额度
	private TextView residue; // 剩余金额
	private TextView earnings; // 年利率
	private TextView percentage; // 购买进度
	private Timer timer;
	private TimerTask mTimerTask;
	private int progress = 0;
	private int Progressbmout; // 进度条购买进度
	private MyProgressbar mProgressBar;
	private TextView mBuyNumber; // 购买人数
	private TextView subscription; // 立即认购
	private String title;
	private String surplus;
	private double balance;
	// private String version;
	private String yuebaoid;
	private RelativeLayout mJoin; // 加入记录
	private RelativeLayout mIntroduce; // 产品介绍
	private String url = com.kkd.kkdapp.Environment.getH5Url() + "day.html";
	private String titleName = "天天赚";
	private RelativeLayout mShare;
	private boolean subscriptionflag;
	private String bmout; // 购买进度
	private TextView min_amount;
	private long lowestAmount;
	private String interests;
	private int maxTime;
	private double rates;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ACCOUNTINFO_CODE_ELSE:
				// Toasttool.MyToast(EveryDayParticularsActivity.this,
				// ACCOUNTINFO_CODE_ELSE);
				break;
			}
		};

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_every_day_particulars);
		initView();
		setListner();
		getMessage();
	}

	/**
	 * 初始化组件
	 */
	public void initView() {
		title_img = (RelativeLayout) this.findViewById(R.id.title_img);
		mTitle = (TextView) this.findViewById(R.id.title);
		mDispark = (TextView) this.findViewById(R.id.money_tv2);
		residue = (TextView) this.findViewById(R.id.residue);
		earnings = (TextView) this.findViewById(R.id.earnings);
		percentage = (TextView) this.findViewById(R.id.percentage);
		mProgressBar = (MyProgressbar) this.findViewById(R.id.increase);
		mBuyNumber = (TextView) this.findViewById(R.id.join_tv2);
		subscription = (TextView) this.findViewById(R.id.subscription);
		mJoin = (RelativeLayout) this.findViewById(R.id.join_record);
		mIntroduce = (RelativeLayout) this.findViewById(R.id.introduce);
		mShare = (RelativeLayout) this.findViewById(R.id.share);
		min_amount = (TextView) this.findViewById(R.id.min_amount);
	}

	/**
	 * 注册监听
	 */
	public void setListner() {
		title_img.setOnClickListener(this);
		subscription.setOnClickListener(this);
		mJoin.setOnClickListener(this);
		mIntroduce.setOnClickListener(this);
		mShare.setOnClickListener(this);
	}

	/**
	 * 获取上个界面的数据
	 */
	public void getMessage() {
		Intent intent = getIntent();
		lowestAmount = intent.getLongExtra("lowestAmount", 0);
		min_amount.setText(String.format("%.2f", lowestAmount * 0.01));
		title = intent.getStringExtra("title"); // 标题
		if (!"".equals(title)) {
			mTitle.setText(title);
		}
		surplus = intent.getStringExtra("surplus"); // 剩余金额
		if (!TextUtils.isEmpty(surplus)) {
			residue.setText(surplus);
			if (Double.parseDouble(surplus) == 0) {
				subscriptionflag = false;
				subscription
						.setBackgroundResource(R.drawable.account_subscription_no);
			} else {
				subscription
						.setBackgroundResource(R.drawable.account_subscription_selector);
				subscriptionflag = true;
			}
		}
		String amount = intent.getStringExtra("amount"); // 开放额度
		if (!"".equals(amount)) {
			mDispark.setText("" + amount);
		}
		interests = intent.getStringExtra("interests"); // 年利率
		if (!"".equals(interests)) {
			earnings.setText(interests);
		}
		bmout = intent.getStringExtra("bmout"); // 购买进度
		if (!"".equals(bmout)) {
			percentage.setText(bmout + "%");
		}
		Progressbmout = intent.getIntExtra("Progressbmout", 0);
		int buyNumSum = intent.getIntExtra("buyNumSum", 0); // 购买人数
		mBuyNumber.setText("" + buyNumSum);
		yuebaoid = intent.getStringExtra("yuebaoid");
		LogUtil.e("YuebaoId", yuebaoid);
		if (timer == null)
			timer = new Timer();
		if (mTimerTask == null)
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					if (progress <= Progressbmout) {
						progress = progress + 1;
						handler.sendEmptyMessage(1);
					} else {
						progress = 0;
						mTimerTask.cancel();
						mTimerTask = null;
						timer.cancel();
						timer = null;
					}

				}
			};
		timer.schedule(mTimerTask, 00, 10);
		maxTime = intent.getIntExtra("RecordTime", 0);
		if (maxTime > 0) {
			subscription.setAlpha(0.5f);
			subscription.setEnabled(false);
			updatePurchaseBtn();
			startTime();
		} else {
			subscription.setAlpha(1.0f);
			subscription.setText("立即认购");
			subscription.setEnabled(true);
		}
		rates = intent.getDoubleExtra("rates", 0);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_img: // 后退
			finish();
			break;
		case R.id.subscription: // 立即认购
			if (AppUtil.isConnect(this)) {
				if (subscriptionflag) {
					if (PreferenceUtils.getInstance().getLogin(this) == 0) { // 登陆验证
						if (PreferenceUtils.getInstance().getAutonym(this) == 1) { // 身份认证
							if (PreferenceUtils.getInstance().getBoundBankCard(
									this) == 1) { // 判定银行卡是否绑定
								intent = new Intent(this,
										EveryDayTenderActivity.class);
								intent.putExtra("title", title);
								intent.putExtra("surplus", surplus);
								intent.putExtra("yuebaoid", yuebaoid);
								intent.putExtra("lowestAmount", lowestAmount);
								intent.putExtra("interests", interests);
								intent.putExtra("rates", rates);
								startActivity(intent);
								finish();
							} else {
								if (balance == 0) {
									intent = new Intent(this,
											ForTenderActivity.class);
									intent.putExtra("enterTypeFlag", 4);
									intent.putExtra("title", title);
									intent.putExtra("surplus", surplus);
									intent.putExtra("yuebaoid", yuebaoid);
									intent.putExtra("lowestAmount",
											lowestAmount);
									intent.putExtra("interests", interests);
									intent.putExtra("rates", rates);
									startActivity(intent);
								} else {
									intent = new Intent(this,
											EveryDayTenderActivity.class);
									intent.putExtra("title", title);
									intent.putExtra("surplus", surplus);
									intent.putExtra("yuebaoid", yuebaoid);
									intent.putExtra("lowestAmount",
											lowestAmount);
									intent.putExtra("interests", interests);
									intent.putExtra("rates", rates);
									startActivity(intent);
								}
							}
						} else {
							intent = new Intent(this, ForTenderActivity.class);
							intent.putExtra("enterTypeFlag", 4);
							intent.putExtra("title", title);
							intent.putExtra("surplus", surplus);
							intent.putExtra("yuebaoid", yuebaoid);
							intent.putExtra("lowestAmount", lowestAmount);
							intent.putExtra("interests", interests);
							intent.putExtra("rates", rates);
							startActivity(intent);
						}
					} else {
						intent = new Intent(this, LoginActivity.class);
						startActivity(intent);
					}
				}
			} else {
				showToast(R.string.network_anomaly);
			}
			break;
		case R.id.join_record: // 加入记录
			intent = new Intent(this, EvetyDayJoinRecordActivity.class);
			intent.putExtra("yuebaoid", yuebaoid);
			startActivity(intent);
			break;
		case R.id.introduce: // 产品介绍
			if (!TextUtils.isEmpty(url)) {
				intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", url);
				intent.putExtra("titleName", titleName);
				intent.putExtra("shareUrl", "");
				startActivity(intent);
			}
			break;
		case R.id.share: // 分享
			String url = com.kkd.kkdapp.Environment.SHARE_ULR + "cpdetail.html";
			toShareURL(EveryDayParticularsActivity.this, url, "快快贷理财",
					"天天赚年化收益8%!每天都有收益进账~推荐给你吧~", R.drawable.share_kkdai_logo);

			break;
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (progress != 0) {
				LogUtil.e("progress", "" + progress);
				if (progress == 99) {
					mProgressBar.setProgress(100);
				} else {
					if (Double.parseDouble(bmout) > 0
							&& Double.parseDouble(bmout) < 1) {
						mProgressBar.setProgress(1);
					} else {
						mProgressBar.setProgress(Progressbmout);
					}
				}
			} else {
				if (Double.parseDouble(bmout) > 0
						&& Double.parseDouble(bmout) < 1) {
					mProgressBar.setProgress(1);
				} else {
					mProgressBar.setProgress(Progressbmout);
				}
			}
		};
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (mTimerTask2 != null) {
			mTimerTask2.cancel();
			mTimerTask2 = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		if (PreferenceUtils.getInstance().getLogin(this) == 0) {
			getAccountInfo();
		}
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = ACCOUNTINFO_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	public static final int PERIOD = 1000;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	private Timer mTimer = new Timer();
	private TimerTask mTimerTask2 = null;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	public TimerHandler mTimerHandler = new TimerHandler(this);
	protected boolean onStarting = false;

	public static class TimerHandler extends Handler {
		WeakReference<EveryDayParticularsActivity> reference;

		public TimerHandler(EveryDayParticularsActivity view) {
			reference = new WeakReference<EveryDayParticularsActivity>(view);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null)
					reference.get().updatePurchaseBtn();
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null)
					reference.get().onTimerFinish();
				break;
			default:
				break;
			}
		}
	}

	public void startTime() {
		mRecordTime = 0;
		if (mTimerTask2 == null) {
			mTimerTask2 = new RecordTimeTask();
			mTimer.schedule(mTimerTask2, 0, PERIOD);
		}
		isRecoding = true;
	}

	public void onTimerFinish() {
		subscription.setAlpha(1.0f);
		subscription.setText("立即认购");
		subscription.setEnabled(true);

	}

	public void updatePurchaseBtn() {
		int dtime = maxTime - mRecordTime;
		// Date time = new Date(dtime*1000);
		// SimpleDateFormat df = new SimpleDateFormat("hh 时 mm 分 ss 秒");
		// String strTime = df.format(time);
		int ss = dtime % 60;
		int mm = (dtime / 60) % 60;
		int hh = dtime / 60 / 60;
		String strTime = String.format("%02d 时 %02d 分 %02d 秒", hh, mm, ss);
		subscription.setText("距下期更新: " + strTime);

	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}
}
